import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MBJavaSingleSlaveGUI extends JFrame {
    private JPanel contentPane;
    private JButton buttonRefresh;
    private JTextArea testTextArea;
//    private JButton buttonCancel;

    public MBJavaSingleSlaveGUI(String[] args) {
        setTitle("MBJavaSingleSlaveGUI");    //设置显示窗口标题
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    //置窗口是否可以关闭
        setVisible(true);
        setContentPane(contentPane);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                super.windowClosed(e);
                System.exit(0);
            }
        });

        getRootPane().setDefaultButton(buttonRefresh);
        int WIDTH = 1024;
        int HEIGHT = 700;
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        Point p = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        setBounds(p.x - WIDTH / 2, p.y - HEIGHT / 2, WIDTH, HEIGHT);
//        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        buttonRefresh.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onRefresh();
            }
        });

//        buttonCancel.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//                onCancel();
//            }
//        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                MBJavaSingleSlave.main(args);

            }
        });

        // 异步获取模拟的各个data值，以及自动刷新
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        if (MBJavaSingleSlave.batDataList == null){
//                            System.out.println("still null, waiting...");
                            Thread.sleep(200);
                        }
                        else {
                            onRefresh();
                            Thread.sleep(1000);
//                            break;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (NullPointerException ee) {
                        try {
                            Thread.sleep(800);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

    }

    private void onRefresh() {
        // add your code here
//        dispose();
//        System.out.println("refresh");
//        System.out.println(MBJavaSingleSlave.batDataList);
//        System.out.println("refresh");
        testTextArea.setText(getAllData());
    }

    public static String getAllData() {
        StringBuilder t = new StringBuilder();
        int i = 1;
        for (byte[] b : MBJavaSingleSlave.batDataList) {
            int offset = 0;
            Data data = new Data();
            for (PointInfo p : PointTable.pointTable) {
                MBJavaSingleSlave.setValueToEntityByPointData(b, offset, data, p);
                offset = offset + p.getLen();
            }
            t.append(i++);
            t.append(": ");
            t.append(data);
            t.append("\n");
        }
        return t.toString();
    }

    private void onCancel() {
        // add your code here if necessary
        dispose();
    }

    public static void main(String[] args) {
        MBJavaSingleSlaveGUI dialog = new MBJavaSingleSlaveGUI(args);
//        dialog.pack();
//        dialog.setVisible(true);
//        System.exit(0);
    }
}
